package group.igfd.manager.biz.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import group.igfd.manager.biz.dao.DrawbackRecordDao;
import group.igfd.manager.biz.entity.DrawbackRecordEntity;
import group.igfd.manager.biz.model.DrawbackRecordModel;
import group.igfd.manager.biz.model.DrawbackRecordVO;
import group.igfd.manager.biz.model.ExcelData;
import group.igfd.manager.biz.service.DrawbackRecordService;
import group.igfd.manager.biz.utils.ObjectToMap;
import io.renren.common.utils.PageUtils;
import io.renren.common.utils.Query;
import io.renren.common.utils.R;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.usermodel.Font;
import org.apache.poi.xssf.usermodel.*;
import org.apache.poi.xssf.usermodel.extensions.XSSFCellBorder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import javax.servlet.http.HttpServletResponse;
import java.awt.Color;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.*;
import java.util.List;


@Service("drawbackRecordService")
public class DrawbackRecordServiceImpl extends ServiceImpl<DrawbackRecordDao, DrawbackRecordEntity> implements DrawbackRecordService {
    private Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private DrawbackRecordDao drawbackRecordDao;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        EntityWrapper<DrawbackRecordEntity> ew = new EntityWrapper<>();
        if (!ObjectUtils.isEmpty(params.get("orderNo"))) {
            ew.like("order_no", params.get("orderNo").toString());
        }
        ew.eq("deleted_flag", 0);
        ew.orderBy("created_at", false);
        Page<DrawbackRecordEntity> page = this.selectPage(
                new Query<DrawbackRecordEntity>(params).getPage(),
                ew
        );
        return new PageUtils(page);
    }

    @Override
    public Map<String, Object> getInfo(Integer id) {
        EntityWrapper<DrawbackRecordEntity> ew = new EntityWrapper<>();
        ew.eq("id", id);
        DrawbackRecordEntity drawbackRecordEntity = this.selectOne(ew);
        if (drawbackRecordEntity == null) {
            Map<String, Object> map = new HashMap<>();
            map.put("isSuccess", false);
            return map;
        } else {
            Map<String, Object> map = ObjectToMap.transBean2Map(drawbackRecordEntity);
            map.put("isSuccess", true);
            List<Map<String, String>> mapList = new ArrayList<>();
            for (String s : drawbackRecordEntity.getImageUrl().split(",")) {
                Map<String, String> m = new HashMap<>();
                m.put("src", s);
                mapList.add(m);
            }
            map.put("images", mapList);
            return map;
        }
    }

    @Override
    public R PassorNoPass(Integer id, Integer states, Integer taxPrice, Integer taxPoint, String reason) {
        //1:通过；2：未通过
        EntityWrapper<DrawbackRecordEntity> wrapper = new EntityWrapper<>();
        wrapper.eq("id", id);
        DrawbackRecordEntity drawbackRecordEntity = this.selectOne(wrapper);
        if (drawbackRecordEntity == null) {
            return R.error("未找到退税记录");
        }
        if (1 == states) {
            drawbackRecordEntity.setStatus(2);
            drawbackRecordEntity.setTaxPrice(taxPrice);
            drawbackRecordEntity.setTaxPoint(taxPoint);
            drawbackRecordEntity.setUpdatedAt(new Date());
        }
        if (2 == states) {
            drawbackRecordEntity.setStatus(5);
            drawbackRecordEntity.setUpdatedAt(new Date());
            drawbackRecordEntity.setReason(reason);
        }
        boolean i = this.updateById(drawbackRecordEntity);
        if (i) {
            return R.ok("保存成功");
        } else {
            return R.error("保存失败");
        }
    }

    @Override
    public R updateStatus(Integer id, Integer status) {
        EntityWrapper<DrawbackRecordEntity> wrapper = new EntityWrapper<>();
        wrapper.eq("id", id);
        DrawbackRecordEntity drawbackRecordEntity = this.selectOne(wrapper);
        if (drawbackRecordEntity == null) {
            return R.error("未找到退税记录");
        }
        //3:确认转账，2：取消转账
        drawbackRecordEntity.setStatus(status);
        drawbackRecordEntity.setUpdatedAt(new Date());
        boolean i = this.updateById(drawbackRecordEntity);
        if (i) {
            return R.ok("保存成功");
        } else {
            return R.error("保存失败");
        }

    }

    @Override
    public PageUtils queryData(Map<String, Object> params) {
        Map<String, Object> map = new HashMap<>();
        if (!ObjectUtils.isEmpty(params.get("orderNo"))) {
            map.put("orderNo", "%" + params.get("orderNo").toString() + "%");
        }
        if (!ObjectUtils.isEmpty(params.get("statusId"))) {
            map.put("statusId", params.get("statusId"));
        }
        //计算limit分页
        int pageNum = Integer.parseInt(params.get("page").toString());
        int limit = Integer.parseInt(params.get("limit").toString());
        int startNum = (pageNum - 1) * limit;//分页开始index
        map.put("startNum", startNum);
        map.put("endNum", limit);
        List<DrawbackRecordModel> publishBuyersEntityList = drawbackRecordDao.queryData(map);
        int count = drawbackRecordDao.queryCount(map);
        Page<DrawbackRecordModel> newPage = new Page<>();
        newPage.setTotal(count);
        newPage.setCurrent(pageNum);
        newPage.setSize(limit);
        newPage.setRecords(publishBuyersEntityList);
        return new PageUtils(newPage);
    }

    @Override
    public void export(HttpServletResponse response, Map<String, Object> params) {

        Map<String, Object> map = new HashMap<>();
        if (!ObjectUtils.isEmpty(params.get("orderNo"))) {
            map.put("orderNo", "%" + params.get("orderNo").toString() + "%");
        }
        if (!ObjectUtils.isEmpty(params.get("statusId"))) {
            map.put("statusId", params.get("statusId"));
        }

        //计算limit分页
        int pageNum = Integer.parseInt(params.get("page").toString());
        int limit = Integer.parseInt(params.get("limit").toString());
        int startNum = (pageNum - 1) * limit;//分页开始index
        map.put("startNum", startNum);
        map.put("endNum", limit);
        List<DrawbackRecordVO> drawbackRecordVOS = drawbackRecordDao.queryDataExport(map);

        ExcelData<DrawbackRecordVO> data = new ExcelData();
        data.setTitles(Arrays.asList("序号", "客户名称", "订单号", "退税方式", "退税金额", "税点", "账号", "开户行", "姓名", "电话", "退税状态", "申请时间", "退税不通过理由"));
        data.setRows(drawbackRecordVOS);
        try {
            response.setContentType("application/vnd.ms-excel");
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode("退税申请记录", "utf-8"));
            exportExcel(response.getOutputStream(), data);
        } catch (Exception e) {
            logger.error(e.getMessage());
        }
    }

    public void exportExcel(OutputStream out, ExcelData<DrawbackRecordVO> data) throws Exception {
        XSSFWorkbook wb = new XSSFWorkbook();
        try {
            XSSFSheet sheet = wb.createSheet("退税申请记录");
            int rowIndex = writeTitlesToExcel(wb, sheet, data.getTitles());
            writeRowsToExcel(wb, sheet, data.getRows(), rowIndex);
            autoSizeColumns(sheet, data.getTitles().size() + 1);
            wb.write(out);
        } finally {
            out.close();
        }


    }

    public int writeRowsToExcel(XSSFWorkbook wb, Sheet sheet, List rows, int rowIndex) {
        int colIndex = 0;

        Font dataFont = wb.createFont();
        dataFont.setFontName("simsun");
        // dataFont.setFontHeightInPoints((short) 14);
        dataFont.setColor(IndexedColors.BLACK.index);

        XSSFCellStyle dataStyle = wb.createCellStyle();
        dataStyle.setAlignment(XSSFCellStyle.ALIGN_CENTER);
        dataStyle.setVerticalAlignment(XSSFCellStyle.VERTICAL_CENTER);
        dataStyle.setFont(dataFont);

        setBorder(dataStyle, BorderStyle.THIN, new XSSFColor(new Color(0, 0, 0)));
        int i = 1;
        for (Object rowData : rows) {
            Row dataRow = sheet.createRow(rowIndex);

            colIndex = 0;
            DrawbackRecordVO model = (DrawbackRecordVO) rowData;

            Cell cell0 = dataRow.createCell(0);
            cell0.setCellValue(i++);
            cell0.setCellStyle(dataStyle);

            Cell cell1 = dataRow.createCell(1);
            cell1.setCellValue(model.getNickname());
            cell1.setCellStyle(dataStyle);

            Cell cell2 = dataRow.createCell(2);
            cell2.setCellValue(model.getOrderNo());
            cell2.setCellStyle(dataStyle);

            Cell cell3 = dataRow.createCell(3);
            cell3.setCellValue(model.getTransferType());
            cell3.setCellStyle(dataStyle);

            Cell cell4 = dataRow.createCell(4);
            cell4.setCellValue(model.getTaxPrice());
            cell4.setCellStyle(dataStyle);

            Cell cell5 = dataRow.createCell(5);
            cell5.setCellValue(model.getTaxPoint());
            cell5.setCellStyle(dataStyle);

            Cell cell6 = dataRow.createCell(6);
            cell6.setCellValue(model.getAccountNo());
            cell6.setCellStyle(dataStyle);

            Cell cell7 = dataRow.createCell(7);
            cell7.setCellValue(model.getBankName());
            cell7.setCellStyle(dataStyle);

            Cell cell8 = dataRow.createCell(8);
            cell8.setCellValue(model.getRealName());
            cell8.setCellStyle(dataStyle);

            Cell cell9 = dataRow.createCell(9);
            cell9.setCellValue(model.getPhone());
            cell9.setCellStyle(dataStyle);

            Cell cell10 = dataRow.createCell(10);
            cell10.setCellValue(model.getStatus());
            cell10.setCellStyle(dataStyle);

            Cell cell11 = dataRow.createCell(11);
            cell11.setCellValue(model.getCreatedAt());
            cell11.setCellStyle(dataStyle);

            Cell cell12 = dataRow.createCell(12);
            cell12.setCellValue(model.getReason());
            cell12.setCellStyle(dataStyle);
            rowIndex++;
        }
        return rowIndex;
    }

    public int writeTitlesToExcel(XSSFWorkbook wb, Sheet sheet, List<String> titles) {
        int colIndex = 0;
        int rowIndex = 0;

        Font titleFont = wb.createFont();
        titleFont.setFontName("simsun");
        ((XSSFFont) titleFont).setBold(true);

        titleFont.setColor(IndexedColors.BLACK.index);

        XSSFCellStyle titleStyle = wb.createCellStyle();
        titleStyle.setAlignment(XSSFCellStyle.ALIGN_CENTER);
        titleStyle.setVerticalAlignment(XSSFCellStyle.VERTICAL_CENTER);
        titleStyle.setFillForegroundColor(new XSSFColor(new Color(182, 184, 192)));
        titleStyle.setFillPattern(XSSFCellStyle.SOLID_FOREGROUND);
        titleStyle.setFont(titleFont);
        setBorder(titleStyle, BorderStyle.THIN, new XSSFColor(new Color(0, 0, 0)));

        Row titleRow = sheet.createRow(rowIndex);

        colIndex = 0;

        for (String field : titles) {
            Cell cell = titleRow.createCell(colIndex);
            cell.setCellValue(field);
            cell.setCellStyle(titleStyle);
            colIndex++;
        }

        rowIndex++;
        return rowIndex;
    }

    public void setBorder(XSSFCellStyle style, BorderStyle border, XSSFColor color) {
        style.setBorderTop(border);
        style.setBorderBottom(border);
        style.setBorderLeft(border);
        style.setBorderRight(border);
        style.setBorderColor(XSSFCellBorder.BorderSide.TOP, color);
        style.setBorderColor(XSSFCellBorder.BorderSide.LEFT, color);
        style.setBorderColor(XSSFCellBorder.BorderSide.RIGHT, color);
        style.setBorderColor(XSSFCellBorder.BorderSide.BOTTOM, color);
    }

    public void autoSizeColumns(Sheet sheet, int columnNumber) {

        for (int i = 0; i < columnNumber; i++) {
            int orgWidth = sheet.getColumnWidth(i);
            sheet.autoSizeColumn(i, true);
            int newWidth = (int) (sheet.getColumnWidth(i) + 100);
            if (newWidth > orgWidth) {
                sheet.setColumnWidth(i, newWidth);
            } else {
                sheet.setColumnWidth(i, orgWidth);
            }
        }
    }
}
